import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { useFormik } from 'formik'
import styles from './index.module.scss'
import * as Yup from 'yup'
import { useDispatch } from 'react-redux'
import { Authorizations, sendCode } from '@/store/action/user'
import { Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useHistory, useLocation } from 'react-router'

type FormValue = {
  mobile: string
  code: string
}

export default function Login() {
  const history = useHistory()

  const location = useLocation<{ from: string }>()
  // console.log(location)

  const dispatch = useDispatch()

  //  重发验证码的秒数
  const [time, setTime] = useState(0)

  //  定时器
  const timerId = useRef(0)

  //  表单验证
  const formik = useFormik({
    initialValues: {
      mobile: '13535337056',
      code: '246810',
    } as FormValue,
    onSubmit: async (values) => {
      console.log(values)
      // 调用 redux 发请求
      await dispatch(Authorizations(values))
      // 提示用户
      Toast.show({ content: '登陆成功' })
      // 跳转页面

      const target = location.state ? location.state.from : '/'

      history.push(target)
    },
    // validate: (values) => {
    //   const error = {} as FormValue
    //   if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
    //     //  校验不通过
    //     error.mobile = '手机号格式错误'
    //   }
    //   if (!/^\d{6}$/.test(values.code)) {
    //     //  校验不通过
    //     error.code = '验证码格式错误'
    //   }
    //   return error
    // },
    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required('必填项')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      code: Yup.string()
        .required('必填')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  })
  // console.log(formik)

  //  获取验证码
  const handleSendCodes = async () => {
    if (time > 0) return
    //  如果手机输入有误，提示错误信息
    if (formik.errors.mobile)
      return Toast.show({ content: formik.errors.mobile })
    await dispatch(sendCode(formik.values.mobile))
    Toast.show({ content: '验证码发送成功' })
    setTime(60)
    //  用ref 创建 定时器 要使用 window
    timerId.current = window.setInterval(() => {
      setTime((time) => {
        if (time === 1) clearInterval(timerId.current)
        return time - 1
      })
    }, 1000)
  }

  useEffect(() => {
    return () => {
      clearInterval(timerId.current)
    }
  }, [])

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <Input
              autoFocus
              type="text"
              className="input"
              name="mobile"
              placeholder="请输入手机号"
              autoComplete="off"
              maxLength={11}
              onBlur={formik.handleBlur}
              errMsg={formik.touched.mobile ? formik.errors.mobile : ''}
              value={formik.values.mobile}
              onChange={formik.handleChange}
            />
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <Input
              value={formik.values.code}
              onChange={formik.handleChange}
              className="input"
              name="code"
              placeholder="请输入验证码"
              maxLength={6}
              autoComplete="off"
              onBlur={formik.handleBlur}
              errMsg={formik.touched.code ? formik.errors.code : ''}
              extra={
                <span onClick={handleSendCodes}>
                  {time === 0 ? '获取验证码' : `${time}秒后重试`}
                </span>
              }
            />
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            className="login-btn"
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
